package com.yang.biz.modular.post.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.common.util.CommonFormatUtil;
import com.yang.biz.modular.post.entity.Instrument;
import com.yang.biz.modular.post.entity.PostRecord;
import com.yang.biz.modular.post.enums.InstrumentDataTypeEnum;
import com.yang.biz.modular.post.enums.InstrumentPostStatusEnum;
import com.yang.biz.modular.post.mapper.InstrumentMapper;
import com.yang.biz.modular.post.param.InstrumentRegisterParam;
import com.yang.biz.modular.post.result.InstrumentPostDataResult;
import com.yang.biz.modular.post.result.InstrumentTableOptionsResult;
import com.yang.biz.modular.post.result.TableDataBean;
import com.yang.biz.modular.post.service.InstrumentService;
import com.yang.biz.modular.post.service.PostRecordService;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: yangjianzhi
 * @version1.0
 */
@Slf4j
@Service
public class InstrumentServiceImpl extends ServiceImpl<InstrumentMapper, Instrument> implements InstrumentService {

    @Resource
    private PostRecordService postRecordService;

//    @Value("${file_server.location}")
    private String location;

    private final String DATE_CODE = "date";

    private final String INSTRUMENT_DIR_NAME = "instrument";

//    private final String STATION_DATA_COLLECT_API = "https://x3deqvid.beesnat.com/stationDataCollect/";
    private final String STATION_DATA_COLLECT_API = "http://120.79.221.57/stationDataCollect/";

    private final String appId = "J8VdVDTw";

    private final String appSecret = "18205c29890c338095d2f1286803d049ad2f9ed7";

    private final String random = "12323";

    @Synchronized
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void postInstrumentData() {
        log.info("=============================================================");
        log.info("开始测试推送数据 {}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        log.info("==登录验证");
        String accessToken = login();
        if (StrUtil.isBlank(accessToken)) {
            log.info("推送数据登录失败，无法继续推送");
            return;
        }
        log.info("==登录验证成功");

        List<Instrument> instruments = this.list();
        List<InstrumentTableOptionsResult> tableOptionsList = scanFile();
        Map<String, Map<String, InstrumentTableOptionsResult>> optionMap = tableOptionsList.stream()
                .filter(item -> StrUtil.isAllNotBlank(item.getInstrName(), item.getTableName()))
                .collect(Collectors.groupingBy(InstrumentTableOptionsResult::getInstrName,
                        Collectors.toMap(InstrumentTableOptionsResult::getTableName, b -> b)));
        log.info("==读取配置及结构, 配置（{}） 结构（{}）", instruments.size(), tableOptionsList.size());

        log.info("==检查是否注册设备");
        for (Instrument instrument : instruments) {
            String instrumentName = instrument.getInstrumentName();
            String tableName = instrument.getTableName();
            String collectionName = getCollectionName(instrumentName, tableName, accessToken);
            if (StrUtil.isBlank(collectionName)) {
                log.info("该设备 {} 未注册, 正在注册", instrumentName);
                this.register(instrument, accessToken);
            } else {
                log.info("{} {} 已注册: {}", instrumentName, tableName, collectionName);
            }
        }

        instruments = this.list();
        for (Instrument instrument : instruments) {
            String instrumentName = instrument.getInstrumentName();
            String tableName = instrument.getTableName();
            log.info("============================================================= 开始 {} - {} 任务", instrumentName, tableName);
            String collectionName = getCollectionName(instrumentName, tableName, accessToken);
            if (StrUtil.isBlank(collectionName)) {
                log.info("error: 该设备 {} {} 未注册, 请及时注册", instrumentName, tableName);
                continue;
            }

            log.info("==获取 {} {} {} 对应配置结构", instrumentName, tableName, collectionName);
            // 获取表结构
            Map<String, InstrumentTableOptionsResult> stringInstrumentTableOptionsResultMap = optionMap.get(instrumentName);
            if (stringInstrumentTableOptionsResultMap == null) {
                log.info("error: 该设备 {} 缺少数据文件，请检查", instrumentName);
                continue;
            }
            InstrumentTableOptionsResult tableOptionsResult = stringInstrumentTableOptionsResultMap.get(tableName);
            if (tableOptionsResult == null) {
                log.info("error: 该设备 {} 缺少 {} 表结构，请检查", instrumentName, tableName);
                continue;
            }

            log.info("==加载推送数据");
            File excelFile = new File(location + File.separator + INSTRUMENT_DIR_NAME + File.separator + instrumentName + ".xlsx");
            int progressIndex = findProgressIndex(excelFile, instrument);
            if (progressIndex == -1) {
                log.info("error: 文件 {}.xlsx - 表{}, 已没有推送数据", instrumentName, tableName);
                continue;
            }
            // 加载数据
            List<InstrumentPostDataResult> dataList = readDataFromExcel(excelFile, instrument, progressIndex);
            int size = dataList.size();
            if (size == 0) {
                log.info("error: 文件{}.xlsx - 表{}, 已没有推送数据", instrumentName, tableName);
                continue;
            }
            log.info("==已加载 {} 条推送数据", size);
            // 推送数据
            TableDataBean tableDataBean = convertExcelToTableDataBean(tableOptionsResult, dataList);
            tableDataBean.setCollectionName(collectionName);
            log.info("==开始推送数据");
            boolean postSuccess = postInstrumentData(tableDataBean, accessToken);
            List<TableDataBean.RowDataBean> dataRowBeanList = tableDataBean.getDataRowBeanList();
            for (TableDataBean.RowDataBean rowDataBean : dataRowBeanList) {
                JSONObject obj = rowDataBean.getData();
                String dateString = obj.getStr(DATE_CODE, "");
                log.info(" {} 数据录入 {}", postSuccess ? "成功" : "失败", dateString);
            }
            if (!postSuccess) {
                for (InstrumentPostDataResult postDataResult : dataList) {
                    postDataResult.setSuccess(false);
                }
            }

            log.info("==推送完成，记录推送信息");
            // 记录信息
            String timeString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LambdaUpdateWrapper<Instrument> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Instrument::getId, instrument.getId());
            updateWrapper.set(Instrument::getTotalPushCount, instrument.getTotalPushCount() + dataList.stream().filter(InstrumentPostDataResult::isSuccess).count());
            updateWrapper.set(Instrument::getLatestPushTime, timeString);
            this.update(updateWrapper);

            // 推送记录
            PostRecord postRecord = new PostRecord();
            postRecord.setInstrumentName(instrumentName);
            postRecord.setTableName(tableName);
            postRecord.setPushTime(timeString);
            postRecord.setPushData(JSONUtil.toJsonStr(dataList));
            postRecordService.save(postRecord);

            log.info("==开始标记推送状态");
            markPostStatus(excelFile, instrument, dataList);
        }
    }

    /**
     * 标记推送状态
     */
    public void markPostStatus(File file, Instrument instrument, List<InstrumentPostDataResult> postDataResultList) {
        String tableName = instrument.getTableName();
        int pushedIndex = instrument.getPushedIndex();
        try {
            FileInputStream fis = new FileInputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheet(tableName);
            if (sheet != null) {
                for (InstrumentPostDataResult postDataResult : postDataResultList) {
                    int rowIndex = postDataResult.getRowIndex();
                    boolean success = postDataResult.isSuccess();
                    Row row = sheet.getRow(rowIndex);
                    if (row != null) {
                        Cell cell = row.createCell(pushedIndex);
                        if (cell != null) {
                            cell.setCellValue(success ? InstrumentPostStatusEnum.YES.getValue()
                                    : InstrumentPostStatusEnum.ERROR.getValue());
                        }
                    }
                }
            }

            // 保存修改后的工作簿到文件中
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);

            // 关闭资源
            fos.close();
            workbook.close();
            fis.close();
            log.info("==标记推送状态完成");
        } catch (IOException exception) {
            exception.printStackTrace();
            log.info("标记推送状态失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public JSONObject register(Instrument instrument, String accessToken) {
        String instrumentName = instrument.getInstrumentName();
        int dataType = instrument.getDataType();
        if (!InstrumentDataTypeEnum.valid(dataType)) {
            dataType = InstrumentDataTypeEnum.Other.getKey();
        }

        File excelFile = new File(location + File.separator + INSTRUMENT_DIR_NAME + File.separator + instrumentName + ".xlsx");
        if (!excelFile.exists()) {
            return JSONUtil.createObj().set("success", false).set("message", instrumentName + "文件不存在");
        }

        // 读取配置
        try (XSSFWorkbook workbook = new XSSFWorkbook(excelFile)) {
            InstrumentRegisterParam instrumentRegisterParam = new InstrumentRegisterParam();
            instrumentRegisterParam.setName(instrumentName);
            instrumentRegisterParam.setDataType(dataType);
            List<InstrumentRegisterParam.TableMeasure> tableMeasures = new ArrayList<>();
            instrumentRegisterParam.setTableMeasures(tableMeasures);

            int numberOfSheets = workbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String tableName = sheet.getSheetName();
                InstrumentTableOptionsResult instrumentTableInfo = getInstrumentTableInfo(sheet, FileUtil.mainName(excelFile));

                InstrumentRegisterParam.TableMeasure tableMeasure = new InstrumentRegisterParam.TableMeasure();
                tableMeasure.setTableName(tableName);
                tableMeasure.setPushedIndex(instrumentTableInfo.getPushedIndex());
                List<InstrumentRegisterParam.MeasureMeta> measureMetas = new ArrayList<>();
                tableMeasure.setMeasureMetas(measureMetas);
                List<InstrumentTableOptionsResult.InstrumentTableColumnsResult> columns = instrumentTableInfo.getColumns();
                for (InstrumentTableOptionsResult.InstrumentTableColumnsResult column : columns) {
                    InstrumentRegisterParam.MeasureMeta measureMeta = new InstrumentRegisterParam.MeasureMeta();
                    String measureCode = column.getMeasureCode();
                    String measureUnit = column.getMeasureUnit();
                    String measureType = column.getMeasureType();

                    measureMeta.setMeasureCode(measureCode);
                    measureMeta.setMeasureName(measureCode);
                    measureMeta.setMeasureType(measureType);
                    measureMeta.setMeasureUnit(measureUnit);
                    measureMetas.add(measureMeta);
                }
                tableMeasures.add(tableMeasure);
            }
            boolean success = registerTable(instrumentRegisterParam, accessToken);
            // 保存配置
            if (success) {
                for (InstrumentRegisterParam.TableMeasure tableMeasure : tableMeasures) {
                    String tableName = tableMeasure.getTableName();
                    int pushedIndex = tableMeasure.getPushedIndex();
                    Instrument theInstrument = this.getOne(new LambdaQueryWrapper<Instrument>().eq(Instrument::getInstrumentName, instrumentName)
                            .eq(Instrument::getTableName, tableName));
                    if (theInstrument == null) {
                        Instrument newInstrument = new Instrument();
                        newInstrument.setInstrumentName(instrumentName);
                        newInstrument.setTableName(tableName);
                        newInstrument.setPushCount(10);
                        newInstrument.setPushedIndex(pushedIndex);
                        newInstrument.setTotalPushCount(0);
                        this.save(newInstrument);
                    } else {
                        LambdaUpdateWrapper<Instrument> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(Instrument::getId, theInstrument.getId());
                        updateWrapper.set(Instrument::getPushedIndex, pushedIndex);
                        this.update(updateWrapper);
                    }
                }
            }
            return JSONUtil.createObj().set("success", success);
        } catch (IOException | InvalidFormatException ignored) {
            return JSONUtil.createObj().set("success", false).set("message", "无法读取文件数据");
        }
    }

    /**
     * 扫描数据文件
     */
    public List<InstrumentTableOptionsResult> scanFile() {
        List<InstrumentTableOptionsResult> resultList = new ArrayList<>();

        File dir = new File(location + File.separator + INSTRUMENT_DIR_NAME);
        if (dir.exists()) {
            List<File> fileList = FileUtil.loopFiles(dir, file -> file.isFile() && "xlsx".equals(FileUtil.getSuffix(file)));
            for (File file : fileList) {
                try (XSSFWorkbook workbook = new XSSFWorkbook(file)) {
                    int numberOfSheets = workbook.getNumberOfSheets();
                    for (int i = 0; i < numberOfSheets; i++) {
                        Sheet sheet = workbook.getSheetAt(i);
                        InstrumentTableOptionsResult instrumentTableInfo = this.getInstrumentTableInfo(sheet, FileUtil.mainName(file));
                        if (instrumentTableInfo == null) {
                            continue;
                        }
                        resultList.add(instrumentTableInfo);
                    }
                } catch (IOException | InvalidFormatException exception) {
                    exception.printStackTrace();
                }
            }
        }

        return resultList;
    }

    /**
     * 在Excel取出数据
     */
    private List<InstrumentPostDataResult> readDataFromExcel(File excelFile, Instrument instrument, int progressIndex) {
        String tableName = instrument.getTableName();
        int pushCount = instrument.getPushCount();
        if (pushCount <= 0) {
            pushCount = 10;
        }
        int endIndex = progressIndex + pushCount - 1;

        ExcelReader reader = ExcelUtil.getReader(excelFile);
        reader.setSheet(tableName);
        List<List<Object>> data = reader.read(progressIndex, endIndex);
        reader.close();
        List<List<String>> dataList = data.stream()
                .map(list -> list.stream()
                        .map(obj -> ObjectUtil.isEmpty(obj) ? "" : obj.toString()).collect(Collectors.toList()))
                .collect(Collectors.toList());

        List<InstrumentPostDataResult> postDataResultList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            List<String> stringList = dataList.get(i);
            InstrumentPostDataResult postDataResult = new InstrumentPostDataResult();
            postDataResult.setRowIndex(progressIndex + i);
            postDataResult.setData(stringList);
            postDataResultList.add(postDataResult);
        }
        return postDataResultList;
    }

    /**
     * 获取进度索引
     */
    private int findProgressIndex(File excelFile, Instrument instrument) {
        String tableName = instrument.getTableName();
        int pushedIndex = instrument.getPushedIndex();

        int progressIndex = -1;
        try (XSSFWorkbook workbook = new XSSFWorkbook(excelFile)) {
            Sheet sheet = workbook.getSheet(tableName);
            if (sheet != null) {
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 3; i < lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    String cellValue = this.getStringCellValue(row, pushedIndex);
                    if (StrUtil.isBlank(cellValue)) {
                        progressIndex = i;
                        break;
                    }
                }
            }
        } catch (IOException | InvalidFormatException ignored) {
        }
        return progressIndex;
    }

    /**
     * 将Excel表格的数据转换为TableDataBean对象
     */
    private TableDataBean convertExcelToTableDataBean(InstrumentTableOptionsResult tableOptionsResult, List<InstrumentPostDataResult> data) {
        List<InstrumentTableOptionsResult.InstrumentTableColumnsResult> columns = tableOptionsResult.getColumns();

        TableDataBean tableDataBean = new TableDataBean();

        // 由于配置和数据都是从excel数据表读取出来的，可一一对应转化
        List<TableDataBean.RowDataBean> rowDataBeans = new ArrayList<>();
        List<String> keyList = new ArrayList<>();
        for (InstrumentTableOptionsResult.InstrumentTableColumnsResult column : columns) {
            keyList.add(column.getMeasureCode());
        }

        for (InstrumentPostDataResult datum : data) {
            TableDataBean.RowDataBean rowDataBean = new TableDataBean.RowDataBean();
            JSONObject obj = JSONUtil.createObj();
            rowDataBean.setData(obj);

            List<String> dataStringList = datum.getData();
            String dateString = dataStringList.get(0);
            long ts = convertStringToTimestamp(CommonFormatUtil.formatDateTime(dateString));
            if (ts == -1) {
                datum.setSuccess(false);
                log.info(" {} 数据录入失败, 时间格式不规范", dateString);
                continue;
            }
            rowDataBean.setId(ts);
            rowDataBean.setTs(ts);
            for (int i = 0; i < keyList.size(); i++) {
                String key = keyList.get(i);
                String value = "";
                if (dataStringList.size() > i) {
                    value = dataStringList.get(i);
                }
                obj.set(key, value);
            }
            rowDataBeans.add(rowDataBean);
        }
        tableDataBean.setDataRowBeanList(rowDataBeans);

        return tableDataBean;
    }

    public static long convertStringToTimestamp(String dateString) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(dateString);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 从Excel表格中获取设备数据表信息，包括表名、列名、单位和类型
     *
     * @param sheet
     * @param fileMainName
     * @return
     */
    private InstrumentTableOptionsResult getInstrumentTableInfo(Sheet sheet, String fileMainName) {
        String sheetName = sheet.getSheetName();

        // 设备数据表信息
        InstrumentTableOptionsResult tableOptionsResult = new InstrumentTableOptionsResult();
        tableOptionsResult.setInstrName(fileMainName);
        tableOptionsResult.setTableName(sheetName);

        // 表结构
        List<InstrumentTableOptionsResult.InstrumentTableColumnsResult> columnsResultList = new ArrayList<>();
        int lastRowNum = sheet.getLastRowNum();
        if (lastRowNum < 3) {
            return null;
        }

        // 读取前四行数据 （配置及一行数据）
        Row preNameRow = sheet.getRow(0);
        Row sufNameRow = sheet.getRow(1);
        Row unitRow = sheet.getRow(2);
        Row dataRow = sheet.getRow(3);
        int cellCount = preNameRow.getLastCellNum();

        // 默认为第一列为时间
        InstrumentTableOptionsResult.InstrumentTableColumnsResult timeColumn = new InstrumentTableOptionsResult.InstrumentTableColumnsResult();
        timeColumn.setMeasureCode(DATE_CODE);
        timeColumn.setMeasureUnit("");
        timeColumn.setMeasureType("STRING");
        columnsResultList.add(timeColumn);
        for (int j = 1; j < cellCount; j++) {
            InstrumentTableOptionsResult.InstrumentTableColumnsResult columnsResult = new InstrumentTableOptionsResult.InstrumentTableColumnsResult();
            String measurePreName = getStringCellValue(preNameRow, j);
            String measureSufName = getStringCellValue(sufNameRow, j);
            columnsResult.setMeasureCode(measurePreName + "-" + measureSufName);
            columnsResult.setMeasureUnit(getStringCellValue(unitRow, j));
            columnsResult.setMeasureType(getMeasureType(dataRow.getCell(j)));
            columnsResultList.add(columnsResult);
        }

        tableOptionsResult.setPushedIndex(cellCount + 1);
        tableOptionsResult.setColumns(columnsResultList);
        return tableOptionsResult;
    }

    /**
     * 格式化单元格值作为字符串
     *
     * @param cell
     * @return
     */
    private String getStringCellValue(Cell cell) {
        DataFormatter dataFormatter = new DataFormatter();
        return dataFormatter.formatCellValue(cell);
    }

    private String getStringCellValue(Row row, int col) {
        return getStringCellValue(row.getCell(col));
    }

    /**
     * 根据cell value获取指标类型
     */
    private String getMeasureType(Cell cell) {
        String type = "";
        try {
            CellType cellType = cell.getCellType();
            switch (cellType) {
                case NUMERIC:
                    // 不考虑，整型情况
                    type = "DOUBLE";
                    break;
                case BOOLEAN:
                    type = "BOOLEAN";
                    break;
                case STRING:
                default:
                    type = "STRING";
                    break;
            }
        } catch (Exception ignored) {
            type = "STRING";
        }
        return type;
    }

    /**
     * 注册设备
     */
    private boolean registerTable(InstrumentRegisterParam instrumentRegisterParam, String token) {
        String url = STATION_DATA_COLLECT_API + "/api/collect/registerInstrument";
        String result = HttpRequest.post(url)
                .header("token", token)
                .body(JSONUtil.toJsonStr(instrumentRegisterParam))
                .execute()
                .body();
        return handleRequestResult(result, url);
    }

    /**
     * 推送数据
     */
    private boolean postInstrumentData(TableDataBean tableDataBean, String token) {
        String url = STATION_DATA_COLLECT_API + "/api/collect/postInstrumentData";
        String result = HttpRequest.post(url)
                .header("token", token)
                .body(JSONUtil.toJsonStr(tableDataBean))
                .execute()
                .body();
        return handleRequestResult(result, url);
    }

    /**
     * 判断设备数据表是否创建
     * <p>
     * 查看数据库表入库最新时间戳接口用于判断数据表是否创建成功
     */
    private String getCollectionName(String instrumentName, String tableName, String token) {
        String url = STATION_DATA_COLLECT_API + "/api/collect/getLastTs";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("instrumentName", instrumentName);
        paramMap.put("tableName", tableName);
        String result = HttpRequest.get(url)
                .header("token", token)
                .form(paramMap)
                .execute()
                .body();
        JSONObject data = getResponseData(result, url);
        if (data == null) {
            return null;
        }
        return data.getStr("collectionName");
    }

    /**
     * 登录
     */
    private String login() {
        String url = STATION_DATA_COLLECT_API + "/login";
        String result = HttpRequest.post(url)
                .body(JSONUtil.createObj().set("appId", appId).set("random", random).set("sign", "fe0798102cb99d6298d0f76afd2d1e9a909467313384fe98898eabc6fbd88ad4").toString())
                .execute()
                .body();
        JSONObject data = getResponseData(result, url);
        if (data == null) {
            return null;
        }
        return data.getStr("accessToken");
    }

    /**
     * 返回数据统一处理
     */
    private JSONObject getResponseData(String result, String url) {
        JSONObject resultJson = JSONUtil.parseObj(result);
        String code = resultJson.getStr("code", "500");
        if ("200".equals(code)) {
            return resultJson.getJSONObject("data");
        }
        log.error("请求地址：" + url);
        log.error("请求错误：" + resultJson.getStr("message"));
        return null;
    }

    /**
     * 处理请求结果，如果返回码为200则返回true，否则记录错误信息并返回false
     */
    private Boolean handleRequestResult(String result, String url) {
        JSONObject resultJson = JSONUtil.parseObj(result);
        String code = resultJson.getStr("code", "500");
        if ("200".equals(code)) {
            log.info("message：" + resultJson.getStr("message"));
            return true;
        }
        log.error("请求地址：" + url);
        log.error("请求错误：" + resultJson.getStr("message"));
        return false;
    }
}
